package com.haixee.parkdemo.gateway.security;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haixee.parkdemo.common.response.CommonResEnum;
import com.haixee.parkdemo.common.response.ResUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class DefaultAccessDeniedHandler implements ServerAccessDeniedHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        return Mono.defer(() -> Mono.just(exchange.getResponse()).flatMap(response -> {
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] result;
            try {
                result = objectMapper.writeValueAsBytes(ResUtil.error(CommonResEnum.PERMISSION_DENIED));
            } catch (JsonProcessingException e) {
                return Mono.error(new RuntimeException(e));
            }
            DataBuffer dataBuffer = dataBufferFactory.wrap(result);
            return response.writeWith(Mono.just(dataBuffer));
        }));
    }
}
